package ashbyutils.database.testing;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import junit.framework.TestCase;

/**
 * <p>
 * You are welcome to do whatever you want to with this source file provided
 * that you maintain this comment fragment (between the dashed lines). Modify
 * it, change the package name, change the class name ... personal or business
 * use ... sell it, share it ... add a copyright for the portions you add ...
 * </p>
 * <p>
 * My goal in giving this away and maintaining the copyright is to hopefully
 * direct developers back to JavaRanch.
 * </p>
 * <p>
 * The original source can be found at <a
 * href=http://www.javaranch.com>JavaRanch</a>
 * </p>
 * <p> - - - - - - - - - - - - - - - - -
 * </p>
 */
public class JndiUnitTestHelperTest extends TestCase {
	private static final String TEST_PROPERTY_FILE = "jndi_unit_test_helper.properties"; //$NON-NLS-1$

	/**
	 * Method tearDown
	 */
	public void tearDown() {
		try {
			JndiUnitTestHelper.shutdown();
		} catch (NamingException ne) {
			ne.printStackTrace();
		}
	}

	/**
	 * Method testGetConnection Simply creates the JNDI DataSource, gets a
	 * connection and frees it. Deemed successful if no exceptions are thrown.
	 */
	public void testGetConnection() {
		// ok so this code usually goes in the setUp but...
		if (JndiUnitTestHelper.notInitialized()) {
			try {
				JndiUnitTestHelper.init(TEST_PROPERTY_FILE);
			} catch (IOException ioe) {
				ioe.printStackTrace();
				fail(ioe.getMessage());
			} catch (NamingException ne) {
				ne.printStackTrace();
				fail(ne.getMessage());
			}
		}
		try {
			InitialContext ctx = new InitialContext();
			DataSource ds = (DataSource) ctx.lookup(JndiUnitTestHelper
					.getJndiName());
			Connection conn = ds.getConnection();
			conn.close();
		} catch (NamingException ne) {
			ne.printStackTrace();
			fail(ne.getMessage());
		} catch (SQLException sqle) {
			sqle.printStackTrace();
			fail(sqle.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
